<template>
	<view class="wallet-page">
		<detail-head url="../mine/mine" type="none"></detail-head>
		<view class="head">
			<view class="balance">{{user.balance || '00.00'}}</view>
			<view class="desc">余额<text>(元)</text></view>
			<view class="desc-2">每日提现次数为1次</view>
		</view>
		<view class="info">
			<view class="content">
				<view class="item">
					<view class="label">余额充值</view>
					<view class="value" @click="openPopup('topup')">
						<view class="back"></view>
					</view>
				</view>
				<view class="item">
					<view class="label">余额提现</view>
					<view class="value" @click="openPopup('withdraw')">
						<view class="back"></view>
					</view>
				</view>
			</view>
		</view>
		<view class="list">
			<app-title text="交易记录" :width="64"></app-title>
			<view class="table-main-item" v-for="item in listData" :key="item.wechatNickname">
				<view class="info">
					<view class="type">{{item.content}}</view>
					<view class="price">
						{{ item.changeType === 'OUTLAY' ? `-${item.tradeAmount}` : `+${item.tradeAmount}`}}
					</view>
				</view>
				<view class="item-time">{{item.createTime}}</view>
			</view>
		</view>

		<view class="guide" v-if="guide">
			<view class="guide-text">点击右上角...<br>选择在浏览器中打开<br>即可正常支付</view>
			<view class="guide-btn">
				<button type="default" @click="guide = false">关闭</button>
			</view>
			<image src="../../static/img/zy.png" mode="aspectFit" alt />
		</view>

		<uni-load-more :contentText="contentText" @clickLoadMore="onClickLoadMore" :status="queryStatus">
		</uni-load-more>

		<uni-popup ref="topup" type="bottom">
			<view class="popup">
				<view class="title">在线充值</view>
				<view class="item">
					<view class="back"></view>
					<view class="label">充值金额</view>
					<view class="value">
						<input type="number" placeholder="充值金额须大于等于100"
							placeholder-style="font-size: 20rpx; padding-left: 10rpx;" v-model="topUpNumber" />
					</view>
				</view>
				<view class="item">
					<view class="back"></view>
					<view class="label">充值方式</view>
					<uni-data-checkbox v-model="topupCheck" selectedColor="#FFBD47" :localdata="range"></uni-data-checkbox>
				</view>
				<button class="topup" type="default" @click="onTopupPay">立即充值</button>
			</view>
		</uni-popup>

		<uni-popup ref="withdraw" type="bottom">
			<view class="withdraw">
				<view class="title">在线提现</view>
				<view class="item">
					<view class="back"></view>
					<view class="label">真实姓名</view>
					<view class="value none">
						<input type="text" v-model="withdrawName" :disabled="user.name !== '' ? true : false" />
					</view>
				</view>
				<view class="item">
					<view class="back"></view>
					<view class="label">身份证号</view>
					<view class="value none" :class="user.idCard !== '' ? 'none' : ''">
						<input type="text" v-model="withdrawidCard" :disabled="user.idCard !== '' ? true : false" />
					</view>
				</view>
				<view class="item">
					<view class="back"></view>
					<view class="label">收款方式</view>
					<view class="value type">
						<view class="bank"></view>
						银行卡
					</view>
				</view>
				<view class="item">
					<view class="back"></view>
					<view class="label">收款账号</view>
					<view class="value">
						<input type="text" placeholder="银行卡号" placeholder-style="font-size: 20rpx; padding-left: 4rpx;"
							v-model="withdrawBankCard" />
					</view>
				</view>
				<view class="item">
					<view class="back"></view>
					<view class="label">提现金额</view>
					<view class="value">
						<input type="number" placeholder="提现金额最低100" @input="onwithdrawNumberChange"
							placeholder-style="font-size: 20rpx; padding-left: 4rpx;" v-model="withdrawNumber" />
					</view>
				</view>
				<view class="hint1">第三方转账手续费率{{withdrawRate}}，手续费{{withdrawFee}}元，实际到账{{income}}元</view>
				<button class="topup" type="default" @click="onInputPwdClick">立即提现</button>
				<view class="hint">1. 提现金额最低100元；</view>
				<view class="hint">2. 银行卡：T+1(最晚T+2)工作日到账，节假日延迟；</view>
				<view class="hint">3. 提现账户姓名必须与账号实名信息一致，否则会打款失败，退回致账户余额。</view>
			</view>
		</uni-popup>

		<uni-popup ref="pwd" type="bottom">
			<view class="pwdpopup">
				<view class="value">
					<view class="item" v-for="i in 6">
						<text>{{ !!valArr.val[i-1] ? '*' : '' }}</text>
					</view>
				</view>
				<view class="hint">密码为6位数字</view>
				<numberKeyboard tabBar ref='KeyboarHid' @input='clickInput' :psdLength='valArr.length'></numberKeyboard>
			</view>
		</uni-popup>
		<view class="">
		</view>
	</view>
</template>

<script>
	import numberKeyboard from '../../component/key-board/key-board.vue'
	import {
		isWeiXin,
		getUserinfo
	} from '../../utils/utils.js'
	import {
		withdraw,
		withdrawFee,
		getPayResult,
		createPayOrder,
		getBalanceFollowPage
	} from '../../request/wallet-api.js'
	import {
		getSysUser
	} from '../../request/mine.js'

	export default {
		components: {
			numberKeyboard
		},
		data() {
			return {
				guide: false,
				// 用户信息
				user: {},
				// 交易数据
				listData: [],
				// 查询参数
				params: {
					condition: "",
					pageNum: 0,
					pageSize: 10
				},
				// 二维码
				imgUrl: '',
				// 没有更多了
				isNoMore: false,
				// 加载状态
				queryStatus: 'more',
				// 各状态文字说明
				contentText: {
					contentdown: "点击加载更多",
					contentrefresh: "正在加载...",
					contentnomore: "没有更多数据了"
				},
				// id
				withdrawUid: '',
				// 姓名
				withdrawName: '',
				// 身份证
				withdrawidCard: '',
				// 银行卡
				withdrawBankCard: '',
				// 提现金额
				withdrawNumber: '',
				// 实际金额
				income: '*',
				withdrawFee: '*',
				withdrawRate: '*',
				// 充值金额
				topUpNumber: '',
				// 是否有充值订单
				paying: false,
				// 定时器
				timer: null,
				// 密码
				smsCode: '',
				// 密码输入框配置
				valArr: {
					val: '',
					length: 6
				},
				topupCheck: 0,
				range: [{
					"value": 0,
					"text": "支付宝"
				}, {
					"value": 1,
					"text": "银行卡"
				}]
			}
		},
		watch: {
			smsCode: {
				handler(n) {
					if (n.length === 6) {
						this.onWithdrawClick()
						this.closePopup('pwd')
						this.smsCode = ''
						this.valArr.val = ''
					}
				}
			}
		},
		created() {
			this.onLoadListData()
			this.user = getUserinfo()
			this.withdrawUid = this.user.id
			this.withdrawName = this.user.name
			this.withdrawidCard = this.user.idCard
			this.withdrawBankCard = this.user.bankCardAccount
		},
		mounted() {
			this.getWithdrawFee()
			let local = uni.getStorageSync('alpay')
			if (!!local) {
				let alpay = JSON.parse(local)
				if (!isWeiXin() && alpay) {
					this.handlerQueryStatus(alpay.code, alpay.time)
				}
			}

			console.log(this.config)
		},

		methods: {
			// 打开
			openPopup(val) {
				if (val === 'topup') {
					if (this.config.topup_btn) {
						if (isWeiXin()) {
							this.guide = true
						} else {
							this.$refs[val].open('buttom')
						}
					} else {
						uni.showToast({
							title: '通道暂时关闭，请耐心等待',
							icon: 'none'
						})
					}
				} else {
					if (this.config.withdraw_btn) {
						this.$refs[val].open('buttom')
					} else {
						uni.showToast({
							title: '通道暂时关闭，请耐心等待',
							icon: 'none'
						})
					}
				}
			},

			//关闭 
			closePopup(val) {
				this.$refs[val].close()
			},

			//输入的值
			clickInput(val) {
				this.valArr.val = val
				this.smsCode = val
			},

			onInputPwdClick() {
				if (!this.withdrawName) {
					uni.showToast({
						title: '请完善真实姓名',
						icon: 'none'
					})
					return false
				}
				if (!this.withdrawidCard) {
					uni.showToast({
						title: '请完善身份证号',
						icon: 'none'
					})
					return false
				}
				if (!this.withdrawNumber) {
					uni.showToast({
						title: '请输入提现金额',
						icon: 'none'
					})
					return false
				}
				if (!this.user.alipayAccount) {
					uni.showToast({
						title: '请设置支付宝账号后，在提交！',
						icon: 'none'
					})
					return false
				}
				if (this.withdrawNumber < 0) {
					uni.showToast({
						title: '请输入正确金额，在提交！',
						icon: 'none'
					})
					return false
				}
				if (this.withdrawNumber < 100) {
					uni.showToast({
						title: '未达到最小提现金额，最小金额为 100',
						icon: 'none'
					})
					return false
				}
				if (!this.withdrawBankCard) {
					uni.showToast({
						title: '请输入银行卡账号',
						icon: 'none'
					})
					return false
				}
				this.closePopup('withdraw')
				this.openPopup('pwd')
			},

			// 点击加载更多
			onClickLoadMore() {
				this.onLoadListData()
			},

			onTopupPay() {
				if (!this.topUpNumber) {
					uni.showToast({
						title: '请输入充值金额',
						icon: 'none'
					})
					return false
				}
				if (this.topUpNumber < 100) {
					uni.showToast({
						title: '金额必须大于等于100元',
						icon: 'none'
					})
					return false
				}
				if (this.topupCheck===0) {
					this.handlerSelectPayThen()
				} else {
					this.handlerBankCardPay()
				}
			},

			// 
			onwithdrawNumberChange() {
				if (this.withdrawNumber >= 100) {
					this.getWithdrawFee()
				} else {
					this.income = '*'
					this.withdrawFee = '*'
				}
			},

			//获取费率实际金额
			async getWithdrawFee() {
				try {
					let {
						code,
						message,
						data
					} = await withdrawFee(this.withdrawNumber ? this.withdrawNumber : 0)
					this.withdrawFee = data.withdrawFee
					this.withdrawRate = data.withdrawRate
					this.income = data.actualWithdrawAmount
				} catch (err) {
					console.log(err)
					uni.showToast({
						title: '服务繁忙',
						icon: 'error'
					})
				}
			},

			// 提现
			async onWithdrawClick() {
				let params = {
					payPassword: this.smsCode,
					withdrawUid: this.withdrawUid,
					name: this.withdrawName,
					idCard: this.withdrawidCard,
					withdrawAmount: this.withdrawNumber * 1,
					bankCardAccount: this.withdrawBankCard
				}

				try {
					let {
						code,
						message,
						data
					} = await withdraw(params)
					if (code === 200) {
						uni.showToast({
							title: '提现成功',
							icon: 'success'
						})
						this.income = '*'
						this.withdrawNumber = ''
						this.handlerRsetUserinfo()
						this.handlerRsetList()
					} else {
						this.income = '*'
						this.withdrawNumber = ''
						this.$refs.withdraw.close()
						uni.showToast({
							title: message,
							icon: 'none'
						})
					}
				} catch (err) {
					this.withdrawNumber = ''
					console.log(err)
					uni.showToast({
						title: '服务繁忙',
						icon: 'error'
					})
				}
			},

			// 充值
			async handlerBankCardPay() {
				if (this.paying) return false
				this.paying = true
				await createPayOrder({
					actualPaymentAmount: this.topUpNumber,
					goodsTitle: '在线充值',
					orderPlatform: 'SEND_WEB',
					productType: 'RECHARGE',
					remark: '在线充值',
					tradeType: 'MWEB',
					frontUrl: 'http://h5.skynfr.cn/pages/wallet/wallet'
					// frontUrl: 'http://vvph.cn:3005/pages/wallet/wallet'
				}).then((res) => {
					if (res.code === 200) {
						this.$refs.topup.close()
						uni.showToast({
							title: '拉起支付中',
							icon: 'none'
						})
						let querystr =
							`?sid=${res.data.sid}&mid=${res.data.mid}&orderCode=${res.data.orderCode}&totalAmount=${res.data.totalAmount}`
						uni.setStorageSync("endTime", new Date().getTime() + 180000)
						window.location.href = 'http://h5.skynfr.cn/pay-h5' + querystr
						uni.setStorageSync("alpay", JSON.stringify({
							code: res.data.orderCode,
							time: 180
						}))
						setTimeout(() => {
							this.topUpNumber = ''
							this.handlerQueryStatus(res.data.orderCode)
						}, 1000);
						this.paying = false
					} else {
						this.topUpNumber = ''
						uni.showToast({
							title: res.message,
							icon: 'none'
						})
						this.paying = false
					}
				}).catch((err) => {
					uni.showToast({
						title: '服务繁忙',
						icon: 'none'
					})
					this.paying = false
				})
			},

			// 充值
			async handlerSelectPayThen() {
				if (this.paying) return false
				this.paying = true
				await createPayOrder({
					actualPaymentAmount: this.topUpNumber,
					goodsTitle: '在线充值',
					orderPlatform: 'SEND',
					productType: 'RECHARGE',
					remark: '在线充值',
					tradeType: 'MWEB',
					frontUrl: window.location.href
				}).then((res) => {
					if (res.code === 200) {
						this.$refs.topup.close()
						uni.showToast({
							title: '拉起支付中',
							icon: 'none'
						})
						uni.setStorageSync("endTime", new Date().getTime() + 180000)
						window.location.href = res.data.url
						uni.setStorageSync("alpay", JSON.stringify({
							code: res.data.orderCode,
							time: 180
						}))
						setTimeout(() => {
							this.topUpNumber = ''
							this.handlerQueryStatus(res.data.orderCode)
						}, 1000);
						this.paying = false
					} else {
						this.topUpNumber = ''
						uni.showToast({
							title: res.message,
							icon: 'none'
						})
						this.paying = false
					}
				}).catch((err) => {
					uni.showToast({
						title: '服务繁忙',
						icon: 'none'
					})
					this.paying = false
				})
			},

			// 更新 用户数据
			handlerRsetUserinfo() {
				getSysUser().then((res) => {
					if (res.code === 200) {
						res.data.login = true
						this.user = res.data
						uni.setStorageSync('user', JSON.stringify(res.data))
					}
				}).catch(() => {
					uni.showToast({
						title: '服务繁忙',
						icon: 'none'
					})
				})
			},

			// 更新消费列表
			handlerRsetList() {
				this.listData = []
				this.params = {
					condition: "",
					pageNum: 0,
					pageSize: 10
				}
				this.onLoadListData()
			},

			// 查询充值状态
			handlerQueryStatus(code, time = 90) {
				let newTime = new Date().getTime()
				let endTime = JSON.parse(uni.getStorageSync('endTime'))
				if (newTime - endTime > 180000) {
					return false
				} else {
					uni.showToast({
						title: '支付结果将在后台更新,请耐心等待',
						icon: 'none'
					})
					let second = Math.abs(parseInt((newTime - endTime) / 1000))
					this.timer = setInterval(() => {
						second--
						console.log(second)
						uni.setStorageSync('alpay', JSON.stringify({
							code: code,
							time: second
						}))
						if (second) {
							getPayResult(code).then((res) => {
								if (res.code === 200) {
									if (res.data) {
										this.$refs.topup.close()
										uni.showToast({
											title: '支付成功',
											icon: 'success'
										})
										clearInterval(this.timer)
										this.handlerRsetUserinfo()
										this.handlerRsetList()
										uni.removeStorageSync('alpay')
									}
								} else {
									clearInterval(this.timer)
									uni.showToast({
										title: res.message,
										icon: 'none'
									})
									uni.removeStorageSync('alpay')
									uni.removeStorageSync('endTime')
								}
							})
						} else {
							uni.showToast({
								title: '支付超时',
								icon: 'none'
							})
							clearInterval(this.timer)
							uni.removeStorageSync('alpay')
							uni.removeStorageSync('endTime')
						}
					}, 2000)
				}
			},

			// 获取全部数据
			async onLoadListData() {
				this.queryStatus = 'loading'
				this.params.pageNum += 1
				try {
					let {
						code,
						message,
						data
					} = await getBalanceFollowPage(this.params)
					if (code === 200) {
						if (this.params.pageNum <= data.totalPage) {
							this.isNoMore = false
							this.listData.push(...data.list)
							this.queryStatus = 'more'
						} else {
							this.isNoMore = true
							this.queryStatus = 'noMore'
						}
					} else {
						this.queryStatus = 'more'
						uni.showToast({
							title: message,
							icon: 'error'
						})
					}
				} catch {
					this.queryStatus = 'more'
					uni.showToast({
						title: '服务繁忙',
						icon: 'error'
					})
				}
			},
		}
	}
</script>

<style lang="scss" scoped>
	.wallet-page {
		width: 100%;
		padding-bottom: 40rpx;
		background: $wallet-back1-url no-repeat;
		background-size: 100% auto;
		background-position: 0 0;
	}

	.head {
		width: 100%;
		height: 440rpx;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: center;

		.balance {
			font-size: 22px;
			font-family: PingFangSC-Medium, PingFang SC;
			font-weight: 500;
			color: #FFBD47;
		}

		.desc {
			line-height: 50rpx;
			font-size: 12px;
			font-family: PingFangSC-Medium, PingFang SC;
			font-weight: 500;
			color: #929B9D;
			margin-top: 20rpx;
			text-align: center;
		}

		.desc-2 {
			font-size: 9px;
			font-family: PingFangSC-Medium, PingFang SC;
			font-weight: 500;
			color: #FFBD47;
		}
	}

	.info {
		width: 100%;
		height: 180rpx;

		.content {
			width: 100%;
			height: 100%;
			padding-top: 45rpx;
			display: flex;

			.item {
				height: 80rpx;
				display: flex;
				align-items: center;
				justify-content: center;
				margin-left: 120rpx;

				.label {
					margin-right: 30rpx;
					font-size: 28rpx;
					font-family: PingFangSC-Medium, PingFang SC;
					font-weight: 500;
					color: #BFCBCD;
				}

				.value {
					width: 72rpx;
					height: 72rpx;
					font-size: 12px;
					font-family: PingFangSC-Medium, PingFang SC;
					font-weight: 500;
					color: #7B7B7B;
					background: linear-gradient(45deg, #050505, #383838);
					border-radius: 12rpx;
					line-height: 60rpx;
					text-indent: 10rpx;

					.back {
						width: 72rpx;
						height: 72rpx;
						background: $wallet-in-url no-repeat;
						background-size: 60% 60%;
						background-position: center center;
					}
				}
			}
		}
	}

	.list {
		padding: 0 40rpx;

		.table-main-item {
			width: 100%;
			min-height: 120rpx;
			margin: 16rpx 0;
			border-bottom: 2rpx solid rgba(151, 151, 151, .2);
			color: #979797;

			.info {
				width: 100%;
				height: 60rpx;
				display: flex;
				align-items: center;
				justify-content: space-between;

				.type {
					font-size: 32rpx;
					font-family: PingFangSC-Medium, PingFang SC;
					font-weight: 500;
					color: #BFCBCD;
				}

				.price {
					font-size: 28rpx;
					font-family: PingFangSC-Medium, PingFang SC;
					font-weight: 500;
					color: #FFBD47;
				}
			}

			.item-time {
				color: #979797;
				font-size: 24rpx;
			}
		}
	}

	.popup,
	.withdraw {
		width: 100%;
		height: 560rpx;
		padding: 0 40rpx;
		background: $login-resetbakc-url no-repeat;
		background-size: 100% 100%;
		background-position: 0 0;
		display: flex;
		flex-direction: column;
		align-items: center;
		padding-top: 40rpx;

		.title {
			line-height: 60rpx;
			font-size: 32rpx;
			font-family: PingFangSC-Medium, PingFang SC;
			font-weight: 500;
			color: #BFCBCD;
			margin-bottom: 40rpx;
		}

		.item {
			width: 100%;
			height: 66rpx;
			display: flex;
			align-items: center;
			position: relative;
			padding: 0 40rpx;
			margin: 20rpx;

			.back {
				width: 66rpx;
				height: 66rpx;
				border-radius: 50%;
				background: linear-gradient(270deg, rgba(141, 141, 141, 0) 0%, #545454 100%);
				opacity: 0.78;
				position: absolute;
				top: 50%;
				left: 20rpx;
				transform: translateY(-50%);
			}

			.label {
				font-size: 14px;
				font-family: PingFangSC-Medium, PingFang SC;
				font-weight: 500;
				color: #BFCBCD;
				text-indent: 20rpx;
				margin-right: 40rpx;
			}

			.value {
				flex: 1;
				height: 66rpx;
				background: linear-gradient(45deg, #050505, #383838);
				border-radius: 12rpx;
				line-height: 60rpx;
				text-indent: 10rpx;
				color: #7B7B7B;

				input {
					width: 100%;
					height: 100%;
					font-size: 28rpx;
					font-family: PingFangSC-Medium, PingFang SC;
					font-weight: 500;
					color: #7B7B7B;
				}
			}

			.none {
				background: none
			}

			.type {
				background: none;
				display: flex;
				align-items: center;
				color: #7B7B7B;

				.icon {
					width: 66rpx;
					height: 66rpx;
					border-radius: 50%;
					background: $wallet-zfb-url no-repeat;
					background-size: 100% 100%;
				}

				.bank {
					width: 66rpx;
					height: 66rpx;
					border-radius: 50%;
					background: $wallet-bank-url no-repeat;
					background-size: 100% 100%;
					background-position: 0 0;

				}
			}
		}

		.topup {
			width: 684rpx;
			height: 88rpx;
			margin: 40rpx 0;
			line-height: 88rpx;
			background: #121212;
			box-shadow: -10px -10px 20px 0px rgba(39, 39, 39, 0.54), 10px 10px 20px 0px rgba(0, 0, 0, 0.83);
			border-radius: 22px;
			border: 1px solid #FFBD47;
			font-size: 14px;
			font-family: SourceHanSansCN-Regular, SourceHanSansCN;
			font-weight: 400;
			color: #FFBD47;
		}
	}

	.withdraw {
		height: 1060rpx;

		.hint1 {
			font-size: 28rpx;
			padding: 0 30rpx;
			color: #7B7B7B;
			text-align: center;
		}

		.hint {
			width: 100%;
			min-height: 40rpx;
			padding: 0 50rpx;
			font-size: 24rpx;
			font-family: PingFangSC-Medium, PingFang SC;
			font-weight: 500;
			color: #7B7B7B;
		}

		.topup {
			margin-top: 30rpx;
		}
	}

	.pwdpopup {
		width: 100%;
		min-height: 300rpx;
		padding: 0 40rpx;
		display: flex;
		flex-direction: column;
		align-items: center;
		padding: 40rpx 0;
		background: #D2D5DB;

		.value {
			display: flex;
			border-radius: 22rpx;
			overflow: hidden;

			.item {
				width: 112rpx;
				height: 94rpx;
				display: flex;
				align-items: center;
				justify-content: center;
				background: #FFFFFF;
				border: 1px solid rgba(151, 151, 151, 0.1);
				font-size: 34px;
				font-family: SFProDisplay-Regular, SFProDisplay;
				font-weight: 400;
				color: #000000;
			}
		}

		.hint {
			margin: 20rpx 0;
		}
	}

	.guide {
		width: 100%;
		height: 100vh;
		position: fixed;
		z-index: 10000 !important;
		top: 0;
		left: 0;
		background: rgba(0, 0, 0, .8);

		.guide-text {
			color: white;
			font-size: 36rpx;
			display: flex;
			justify-content: center;
			margin: 160rpx 0;
		}

		.guide-btn {
			display: flex;
			justify-content: center;

			button {
				width: 684rpx;
				height: 88rpx;
				line-height: 88rpx;
				background: #121212;
				box-shadow: -10px -10px 20px 0px rgba(39, 39, 39, 0.54), 10px 10px 20px 0px rgba(0, 0, 0, 0.83);
				border-radius: 22px;
				border: 1px solid #FFBD47;
				font-size: 14px;
				font-family: SourceHanSansCN-Regular, SourceHanSansCN;
				font-weight: 400;
				color: #FFBD47;
			}
		}

		image {
			height: 150px;
			position: absolute;
			right: -200rpx;
			top: 0;
		}
	}
</style>
